package com.sun.controller;

import com.sun.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller
@SessionAttributes(value = {"msg"})
public class OutPutController {

    @RequestMapping("/handle01")
    public String handle01(Map<String,Object> map){
        map.put("msg","hello");
        System.out.println(map.getClass());
        return "success";
    }
    @RequestMapping("/handle02")
    public String handle02(Model model){
        model.addAttribute("msg","hello Model");
        System.out.println(model.getClass());
        return "success";
    }

    @RequestMapping("/handle03")
    public String handle03(ModelMap model){
        model.addAttribute("msg","hello ModelMap");
        System.out.println(model.getClass());
        return "success";
    }

    @RequestMapping("/handle04")
    public ModelAndView handler04(){
        //可在构造器中添加视图名，视图名解析器最终会完成拼串得到页面的真实地址
        ModelAndView modelAndView=new ModelAndView("success");
        modelAndView.addObject("msg", "hello ModelAndView");
        return modelAndView;
    }

    @RequestMapping("/handle05")
    public String handler05(User user){
        System.out.println("表单中提取的user="+user);
        return "success";
    }
    @RequestMapping("/handle06")
    public String handler06(@ModelAttribute("abc") User user){
        System.out.println("表单中提取的user="+user);
        return "success";
    }

    @ModelAttribute
    public void getUser(@RequestParam(value="id",required=false) Integer id, Map<String,Object> map){
            if(id!=null){
                //模拟从数据库中获取到的user对象
                User user = new User(1,"Tom","123456","tom@atguigu.com",12);
                System.out.println("从数据库中查询的对象：user="+user );
                //map.put("user", user);
                map.put("abc", user);
            }
    }
}
